package com.nervenets.web.controller;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MethodTypeModel;
import com.nervenets.web.entity.ParamModel;
import com.nervenets.web.enumeration.Method;
import com.nervenets.web.hibernate.dao.UserDao;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author joe
 * Created at 14-4-8 下午4:13
 */
@Controller
@RequestMapping("/docs")
public class DocsController {
    private final static String DOCS_SESSION_ID = "DOCS_SESSION_ID";
    @Resource
    UserDao userDao;

    @RequestMapping("/api/v1")
    String doc1(Model model, HttpServletRequest request) throws Exception {
        String attribute = (String) request.getSession().getAttribute(DOCS_SESSION_ID);
        if (null == attribute) return "redirect:/docs";

        List<MethodTypeModel> apis = new ArrayList<>();
        for (Method method : Method.values()) {
            Handler handler = method.getHandler();
            if (null != handler) {
                MethodTypeModel methodTypeModel = new MethodTypeModel(method.getType());
                if (apis.contains(methodTypeModel)) {
                    final int indexOf = apis.indexOf(methodTypeModel);
                    apis.get(indexOf).addApi(new ParamModel(method, handler.getParams(), handler.result()));
                } else {
                    methodTypeModel.addApi(new ParamModel(method, handler.getParams(), handler.result()));
                    apis.add(methodTypeModel);
                }
            }
        }
        model.addAttribute("apiTypes", apis);
        return "views/stc/api1doc";
    }

    @RequestMapping
    String loginView(HttpServletRequest request) {
        String attribute = (String) request.getSession().getAttribute(DOCS_SESSION_ID);
        if (null == attribute) return "views/stc/login";
        return "redirect:/docs/api/v1";
    }

    @RequestMapping("/login")
    String login(Model model, HttpServletRequest request) {
        String username = ServletRequestUtils.getStringParameter(request, "username", null);
        String password = ServletRequestUtils.getStringParameter(request, "password", null);
        boolean success = false;
        if (!StringUtils.hasAnyEmpty(username, password) && "admin".equalsIgnoreCase(username) && "P@ssw0rd".equalsIgnoreCase(password)) {
            success = true;
            request.getSession().setAttribute(DOCS_SESSION_ID, "接口人员");
        }
        if (!success) {
            model.addAttribute("error", true);
        }
        return success ? "redirect:/docs/api/v1" : "views/stc/login";
    }
}
